from Tools import GetValue, ApiError
import urllib2
from xml.dom import minidom

class King :  
    def __init__(self):
        self.id = None
        self.neutral = None
        self.nickname = None
        self.squares = None
              
    def FromXml(self, xmlElement):
        self.id = int(GetValue(xmlElement.getElementsByTagName("id")[0]))
        self.neutral = GetValue(xmlElement.getElementsByTagName("neutral")[0]).lower()=="true"
        if not self.neutral :
            self.nickname = GetValue(xmlElement.getElementsByTagName("nickname")[0])
            self.squares = int(GetValue(xmlElement.getElementsByTagName("squares")[0]))

class Kings :
    def __init__(self):
        self.kings = {}
    
    def GetKing(self, i):
        if i not in self.kings :
            print 'http://sqwareaapi.cloudapp.net/kings/%d' % (i)
            f = urllib2.urlopen('http://sqwareaapi.cloudapp.net/kings/%d' % (i))
            rep = minidom.parse(f)
            
            xmlElt = rep.getElementsByTagName("kings")
            if len(xmlElt)!=1 :
                raise ApiError("Map API error")
                
            xmlElt = xmlElt[0].getElementsByTagName("king")
            if len(xmlElt)!=1 :
                raise ApiError("Map API error")
                
            xmlElt = xmlElt[0]
            
            k = King()
            k.FromXml(xmlElt)
            self.kings[i] = k
            
        return self.kings[i]
        